<script setup lang="ts">
/**
 * 用户管理页面
 */

/* 引入 */
import { ref, reactive, inject, onMounted } from "vue";
import { ElMessage } from "element-plus";

/* 数据 */
const axios = inject("$axios");

const users = ref([]);

const addDialogVisible = ref(false);

const editDialogVisible = ref(false);

// 添加表单数据
const form = reactive({
  username: "",
  email: "",
  role: "",
  password: "",
});

// 修改表单数据
const editForm = reactive({
  username: "",
  email: "",
  updateData: {
    username: "",
    email: "",
    role: "",
    password: "",
  },
});

/* 钩子 */
onMounted(() => {
  // 发送请求获取用户列表
  axios
    .get("/users/list")
    .then((res) => {
      users.value = res.data;
    })
    .catch((err) => {
      console.error("获取用户列表失败:", err);
    });
});

/* 回调 */
// 修改用户回调
const editUser = (user) => {
  // 自动获取用户信息填入修改表单
  editForm.username = user.username;
  editForm.email = user.email;
  editDialogVisible.value = true;

  // 默认填充原有的数据
  editForm.updateData = {
    username: user.username,
    email: user.email,
    role: user.role,
    password: "123456",
  };

  ElMessage({
    message: "默认直接提交修改时, 修改密码为 '123456', 请注意!",
    type: "warning",
  });
};

// 删除用户回调
const deleteUser = (user) => {
  axios
    .delete("/users", {
      data: {
        email: user.email,
        username: user.username,
      },
    })
    .then(() => {
      users.value = users.value.filter((t) => t._id !== user._id); // 更新前端用户列表(这句很好, 可以不用发起请求)
      ElMessage({
        message: `已删除用户：${user.username}`,
        type: "success",
      });
    })
    .catch((err) => {
      console.error("删除用户失败:", err);

      ElMessage({
        message: "删除用户失败，请稍后再试！",
        type: "error",
      });
    });
};

// 添加用户回调
const addUser = () => {
  addDialogVisible.value = true;
};

// 提交添加用户表单回调
const submitAddUserForm = () => {
  // 校验表单数据
  if (!form.username || !form.email || !form.role || !form.password) {
    ElMessage({
      message: "请填写完整的用户信息!",
      type: "error",
    });
    return;
  }

  // 提交表单数据
  axios
    .post("/users", {
      username: form.username,
      email: form.email,
      role: form.role,
      password: form.password,
    })
    .then((res) => {
      ElMessage({
        message: `已添加用户: ${res.data.username}`,
        type: "success",
      });

      users.value.push(res.data); // 更新用户列表(也是一种无需发起请求的更新方式)
    })
    .catch((err) => {
      console.error("添加用户失败:", err);
      ElMessage({
        message: "添加用户失败, 请检查输入信息!",
        type: "error",
      });
      addDialogVisible.value = false; // 关闭弹窗
    });

  addDialogVisible.value = false; // 关闭弹窗
};

// 提交修改用户表单回调
const submitEditUserForm = () => {
  // 校验表单数据
  if (!editForm.updateData.role || !editForm.updateData.password) {
    ElMessage({
      message: "请填写要修改的信息选项!",
      type: "error",
    });
    return;
  }

  // 提交更新请求
  axios
    .put("/users", {
      email: editForm.email,
      username: editForm.username,
      updateData: editForm.updateData,
    })
    .then((res) => {
      // 更新列表
      const updatedUser = res.data.updatedUser; // 获取更新后的完整用户数据

      const index = users.value.findIndex(
        (user) => user._id === updatedUser._id, // 找到并更新用户列表中的对应用户
      );

      if (index !== -1) {
        users.value[index] = updatedUser; // 使用更新后的用户数据替换对应用户
      }

      // 成功提示
      ElMessage({
        message: `用户信息修改成功！`,
        type: "success",
      });
      editDialogVisible.value = false; // 关闭对话框
    })
    .catch((err) => {
      // 错误提示
      ElMessage({
        message: "修改用户失败, 请稍后重试!",
        type: "error",
      });
    });
};
</script>

<template>
  <div class="user-page">
    <el-card class="page-card">
      <template #header>
        <h2>管理员-用户管理</h2>
      </template>
      <!-- 添加表单组件 -->
      <div class="add-form-dialog">
        <el-dialog v-model="addDialogVisible" title="添加用户" width="500">
          <el-form :model="form">
            <el-form-item label="昵称" prop="username">
              <el-input v-model="form.username" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-select v-model="form.role" placeholder="请选择用户角色">
                <el-option label="管理员" value="admin" />
                <el-option label="商家" value="merchant" />
              </el-select>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="addDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitAddUserForm"
                >添加</el-button
              >
            </div>
          </template>
        </el-dialog>
      </div>
      <!-- 修改表单组件 -->
      <div class="edit-form-dialog">
        <el-dialog v-model="editDialogVisible" title="修改用户" width="500">
          <el-form :model="editForm">
            <!-- 修改昵称 -->
            <el-form-item label="昵称" prop="username">
              <el-input
                v-model="editForm.updateData.username"
                placeholder="请输入昵称"
              />
            </el-form-item>
            <!-- 修改邮箱 -->
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="editForm.updateData.email"
                placeholder="请输入邮箱"
              />
            </el-form-item>
            <!-- 修改角色 -->
            <el-form-item label="角色" prop="role">
              <el-select
                v-model="editForm.updateData.role"
                placeholder="请选择用户角色"
              >
                <el-option label="管理员" value="admin" />
                <el-option label="商家" value="merchant" />
              </el-select>
            </el-form-item>
            <!-- 修改密码 -->
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="editForm.updateData.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="editDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitEditUserForm">
                修改
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <!-- 页面标题组件 -->
      <div class="header">
        <h3>用户列表</h3>
        <el-button type="primary" @click="addUser">添加用户</el-button>
      </div>
      <!-- 用户列表组件 -->
      <div class="table">
        <el-table :data="users" style="width: 100%" border stripe>
          <el-table-column prop="username" label="用户名称" />
          <el-table-column prop="email" label="用户邮箱" />
          <el-table-column prop="_id" label="用户标识" />
          <el-table-column prop="role" label="用户权限" />
          <el-table-column label="用户操作">
            <template #default="{ row }">
              <el-space wrap :size="10">
                <el-button type="primary" size="small" @click="editUser(row)">
                  修改
                </el-button>
                <el-button type="danger" size="small" @click="deleteUser(row)">
                  删除
                </el-button>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.user-page {
  padding: 20px;
  background-color: #f5f5f5;
}

.page-card {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.el-table {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}
</style>
